import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SumSinRun {
    private int upperBound;
    private int lowerBound;
    private int nThreads;
    private long time;
    //----------------------------------------------------------------------
    public SumSinRun(int upperB, int lowerBound) {
        this.upperBound = upperB;
        this.lowerBound = lowerBound;
        this.nThreads = nThreads;
    }
    //----------------------------------------------------------------------
    public double calculete() {
        time = System.currentTimeMillis();          //Dimension of time and start the timers
             //System.nanoTime();                   //Work of the method depends on the platform and power PC
        double result = 0.0;

        List<Thread> threads = new LinkedList<Thread>();
        List<SumSinRun> ssr = new LinkedList<SumSinRun>();

        int distance = (int) ((Math.abs(upperBound-lowerBound)) / nThreads);
        for (int i = 0; i < nThreads; i++) {
            Thread current;
            SumSinRun sinRun;
            if (i == nThreads - 1 && nThreads != 1) {
                sinRun = new SumSinRun(lowerBound + distance * i + 1, upperBound+1);
                current = new Thread(String.valueOf(sinRun));
            } else if (i == nThreads - 1 && nThreads == 1) {
                sinRun =new SumSinRun(lowerBound + distance * i, upperBound+1);
                current = new Thread(String.valueOf(sinRun));
            } else if (i == 0) {
                sinRun =new SumSinRun(lowerBound + distance * i,
                        lowerBound + distance * (i + 1));
                current = new Thread(String.valueOf(sinRun));
            } else {
                sinRun =new SumSinRun(lowerBound + distance * i + 1,
                        lowerBound + distance * (i + 1));
                current = new Thread(String.valueOf(sinRun));
            }

            current.start();
            threads.add(current);
            ssr.add(sinRun);
        }

        for (int i=0; i<threads.size(); i++) {
            try {
                threads.get(i).join();
                result += ssr.get(i).getTimeCalculete();
            } catch (InterruptedException ex) {
                Logger.getLogger(SumSinCal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        time = System.currentTimeMillis() - time;
        return result;
    }
    //----------------------------------------------------------------------
    public long getTimeCalculete() {
        return time;
    }
    //----------------------------------------------------------------------
}//End class SumSinRun
